package com.kevis.zhunblog.admin.controller.modules.article;

import com.github.pagehelper.PageInfo;
import com.kevis.common.utils.expand.StringKevis;
import com.kevis.webCommon.web.domain.response.Result;
import com.kevis.webCommon.web.domain.response.module.ResultTable;
import com.kevis.webCommon.web.domain.response.module.ResultTree;
import com.kevis.zhunblog.admin.controller.base.Common_ClassController;
import com.kevis.zhunblog.core.dto.PageDomain;
import com.kevis.zhunblog.core.dto.query.CommonClassQuery;
import com.kevis.zhunblog.core.entities.ClassArticleEntity;
import com.kevis.zhunblog.service.ClassArticleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.CacheManager;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

import static com.kevis.webCommon.web.domain.response.Result.decide;
import static com.kevis.webCommon.web.domain.response.Result.failure;

/**
 * ArticleClassController
 *
 * @Author kevis
 * @Date 2023/4/18 16:23
 */
@RestController
@RequestMapping("/article/class/")
public class ArticleClassController extends Common_ClassController {
    @Autowired
    private ClassArticleService classArticleService;

    @Autowired
    CacheManager cacheManager;

    public ArticleClassController() {
        TableName = "article";
        pageTitle = "资讯";
        MODULE_PATH = "modules/article/class/";
    }

    @GetMapping("{template}/main")
    public ModelAndView main(@PathVariable(name = "template", required = false) String template) {
        return jumpPage(MODULE_PATH + template + "/main");
    }

    @GetMapping("data")
    public ResultTable data(PageDomain pageDomain, CommonClassQuery query) {
        //CommonClassQuery query = new CommonClassQuery();

        //PageDomain pageDomain = new PageDomain();
        PageInfo<ClassArticleEntity> pageList = classArticleService.getPageList(query, pageDomain);
        return pageTable(pageList.getList(), pageList.getTotal());
    }

    /**
     * 获取权限列表数据
     *
     * @return
     */
//    @PostMapping("list")
//    public ResultTable postlist(@RequestBody ClassArticleEntity classArticleEntity) {
//        List<ClassArticleEntity> list = classArticleService.listData(classArticleEntity);
//        return pageTable(list,list.size());
//    }

    /**
     * 获取分页列表数据
     *
     * @return
     */
    @PostMapping("{template}/list")
    public Object pagelist(@PathVariable(name = "template", required = false) String template) {
        CommonClassQuery query = new CommonClassQuery();
        query.setSearchParentId(new StringKevis(request.getParameter("SearchParentId")).defaultIsNullOrEmpty(0));
        query.setSearchStatus(new StringKevis(request.getParameter("SearchMarkStatus")).defaultIsNullOrEmpty(9999));
        query.setSearchName(request.getParameter("SearchName"));
        query.setSearchValue(request.getParameter("SearchValue"));
        query.setSearchTimeType(new StringKevis(request.getParameter("SearchTimeType")).defaultIsNullOrEmpty(0));
        query.setSearchTimeBegin(new StringKevis(request.getParameter("SearchTimeBegin")).defaultIsNullOrEmpty(LocalDateTime.now().plusYears(-1)));
        query.setSearchTimeEnd(new StringKevis(request.getParameter("SearchTimeEnd")).defaultIsNullOrEmpty(LocalDateTime.now()));

        PageDomain pageDomain = new PageDomain();
        PageInfo<ClassArticleEntity> pageList = classArticleService.getPageList(query, pageDomain);
//        Cache ca = cacheManager.getCache("ca");
//        if (ca != null) {
//            Cache.ValueWrapper bb = ca.get("getPageList");
//            if (bb != null) {
//                System.out.println(bb.get());
//            }
//        }
        if ("easyui".equalsIgnoreCase(template))
            return pageEasyuiTable(pageList.getList(), pageList.getTotal());
        return pageTable(pageList.getList(), pageList.getTotal());
    }

//    @PostMapping("lefttreelist")
//    public List GetTreeAjax(@PathVariable("tableName") String tableName
//            , @RequestParam(required = false) Integer parentId
//            , @RequestParam(defaultValue = "0", required = false, name = "id") Integer id
//            , @RequestParam(defaultValue = "false", required = false) Boolean isRoot
//            , @RequestParam(defaultValue = "false", required = false) Boolean isThis
//            , @RequestParam(defaultValue = "false", required = false) Boolean isAllStatus
//            , @RequestParam(required = false) String Default
//    ) {
//
//    }

//    /**
//     * 获取权限列表数据
//     *
//     * @return
//     */
//    @PostMapping("treelist")
//    public ResultTable treelist() {
//        List<ClassArticleEntity> list = classArticleService.list();
//        return treeTable(list);
//    }

    @GetMapping("{Template}/add")
    public ModelAndView add(@PathVariable String Template) {
        ClassArticleEntity entity = new ClassArticleEntity();
        ModelAndView modelAndView = jumpPage(MODULE_PATH + Template + "/edit");
        modelAndView.addObject("model", entity);
        //modelAndView.addObject("parentClassUrl", "'?TableName=" + TableName + "&parentId=0&isRoot=true&IsAllStatus=false&parentId=0'");
        return modelAndView;
    }

    /**
     * Describe: 获取父级选择数据
     * Param classArticleEntity
     * Return Result
     */
    @PostMapping("selectParent")
    public ResultTree selectParent(@RequestParam("parentId") Integer parentId) {
        //List<ClassArticleEntity> list = classArticleService.list();
        //List<ClassArticleEntity> list = classArticleService.listMenu(classArticleEntity);
        List<ClassArticleEntity> list = classArticleService.selectByParentId(parentId);
//        ClassArticleEntity baseClass = new ClassArticleEntity();
//        baseClass.setTitle("顶级分类");
//        baseClass.setId(0);
//        baseClass.setParentId(-1);
//        list.add(baseClass);
        return dataTree(list);
//        return null;
    }

    /**
     * Describe: 保存分类信息
     * Param: classArticleEntity
     * Return: ResultBean
     */
    @PostMapping("{Template}/add")
    public Result save(@PathVariable String Template
            , @RequestParam Map<String, Object> params
            , @Validated ClassArticleEntity classArticleEntity)
    //,@RequestBody ClassArticleEntity classArticleEntity)
    {
        if (classArticleEntity.getParentId() == null) {
            return failure("请选择上级菜单");
        }
        String classPath = ",0,";
        ClassArticleEntity parentModel = null;
        if (classArticleEntity.getParentId() > 0)
            parentModel = classArticleService.getById(classArticleEntity.getParentId());
        int classLevel = 1;
        if (parentModel != null) {
            classLevel = parentModel.getClassLevel() + 1;
            if (StringUtils.hasLength(parentModel.getClassPath()))
                classPath = parentModel.getClassPath() + parentModel.getId() + ",";
            else
                classPath = parentModel.getId().toString() + ",";
        }
        classArticleEntity.setClassPath(classPath);
        classArticleEntity.setClassLevel(classLevel);
        boolean result = classArticleService.save(classArticleEntity);
        return decide(result);
    }

    /**
     * Describe: 获取分类修改视图
     * Param ModelAndView
     * Return 权限修改视图
     */
    @GetMapping("{Template}/edit")
    //@PreAuthorize("hasPermission('/system/power/edit','sys:power:edit')")
    public ModelAndView edit(@PathVariable String Template, Model model, String id) {
//        ModelAndView modelAndView = jumpPage(MODULE_PATH + Template + "/edit");
//        modelAndView.addObject("model", classArticleService.getById(id));
//        return  modelAndView;
        model.addAttribute("model", classArticleService.getById(id));
        return jumpPage(MODULE_PATH + Template + "/edit");
    }

    /**
     * Describe: 修改分类信息
     * Param SysPower
     * Return 执行结果
     */
    @PutMapping(value = "{Template}/edit")
    //@PreAuthorize("hasPermission('/system/power/edit','sys:power:edit')")
    public Result edit(//@RequestBody ClassArticleEntity classArticleEntity
                       @RequestParam Map<String, Object> params
            , @Validated ClassArticleEntity classArticleEntity
    ) {
        if (classArticleEntity.getParentId() == null) {
            return failure("请选择上级菜单");
        }
        String classPath = ",0,";
        ClassArticleEntity parentModel = null;
        if (classArticleEntity.getParentId() > 0)
            parentModel = classArticleService.getById(classArticleEntity.getParentId());
        int classLevel = 1;
        if (parentModel != null) {
            classLevel = parentModel.getClassLevel() + 1;
            if (StringUtils.hasLength(parentModel.getClassPath()))
                classPath = parentModel.getClassPath() + parentModel.getId() + ",";
            else
                classPath = parentModel.getId().toString() + ",";
        }
        classArticleEntity.setClassPath(classPath);
        classArticleEntity.setClassLevel(classLevel);
        classArticleEntity.setUpdateTime(LocalDateTime.now());
        boolean result = classArticleService.updateById(classArticleEntity);
        return decide(result);
    }

    /**
     * Describe: 根据 id 进行删除
     * Param id
     * Return Result
     */
    @DeleteMapping("remove/{id}")
    //@PreAuthorize("hasPermission('/system/power/remove','sys:power:remove')")
    public Result remove(@PathVariable Integer id) {
        if (classArticleService.selectByParentId(id).size() > 0) {
            return failure("请先删除下级记录");
        }
        boolean result = classArticleService.removeById(id);
        return decide(result);
    }

    /**
     * Describe: 清除缓存
     * Return Result
     */
    @DeleteMapping("clearCache")
    public Result clearCache() {
        classArticleService.clearCache("","");
        return decide(true);
    }
}
